<?php

namespace app\api\controller;

use app\BaseController;
use Stripe\PaymentIntent;
use Stripe\Stripe;
use think\App;

class Test extends BaseController
{
    public function __construct(App $app)
    {
        Stripe::setApiKey('sk_test_51PSv6vP8CzEc8I987fn4zeATdp21N2VPYuJZWI67iXerS85tvUk8bZFhMbj4hrlDtiRRH157Zkkni4Kd2vjAVGqr00gP4WwuaY');
    }

    public function createPaymentSession()
    {
        try {
            $domain = 'https://hugemaxapi.bscdhk.com';
            $order_id = request()->post('order_id');

            $success_url = $domain . '/api/actionNotify?orderid=' . $order_id;
            $cancel_url  = $domain . '/api/stripeError?orderid=' . $order_id;

            // 查询订单详细信息
            $order = \app\model\OrderDetail::where('order_id', $order_id)
                ->field('id, order_id, price, num,product_id')
                ->select()
                ->toArray();

            $line_items = [];

            foreach ($order as $product) {
                // 动态创建 Stripe 价格 ID
                $price = \Stripe\Price::create([
                    'unit_amount' => $product['price'] * 100, // 将价格转换为分
                    'currency' => 'hkd',
                    'product_data' => [
                        'name' => \app\model\Product::where('id',$product['product_id'])->value('name'), // 可以根据订单产品生成名称
                    ],
                ]);
//                dd($price);
                // 将生成的价格 ID 添加到 line_items 中
                $line_items[] = [
                    'price' => $price->id, // 使用刚刚创建的 Stripe 价格 ID
                    'quantity' => $product['num'], // 商品数量
                ];
            }

            // 创建 Stripe Checkout 会话
            $checkout_session = \Stripe\Checkout\Session::create([
                'line_items'  => $line_items,
                'mode'        => 'payment',
                'success_url' => $success_url,
                'cancel_url'  => $cancel_url,
                'metadata'    => [
                    'order_id' => $order_id,
                ],
            ]);

            return json([
                'url' => $checkout_session->url,
            ]);

        } catch (\Exception $e) {
            return json(['error' => $e->getMessage()], 500);
        }
    }

    /**
     * 支付成功后的回调（Webhook）
     */
    public function webhook()
    {
        $endpoint_secret = 'whsec_YourWebhookSecret';

        $payload = @file_get_contents('php://input');
        $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
        $event = null;

        try {
            $event = \Stripe\Webhook::constructEvent(
                $payload, $sig_header, $endpoint_secret
            );
        } catch (\UnexpectedValueException $e) {
            http_response_code(400);
            exit();
        } catch (\Stripe\Exception\SignatureVerificationException $e) {
            http_response_code(400);
            exit();
        }

        if ($event['type'] == 'payment_intent.succeeded') {
            $paymentIntent = $event['data']['object'];
            // 处理支付成功后的逻辑，例如更新订单状态
        }

        http_response_code(200);
    }

}